"""
插件管理API接口
"""
from flask import Blueprint, request, jsonify, render_template, current_app
from apps.extensions.PluginManager import (
    upload_plugin_dynamic,
    enable_plugin as manager_enbable_plugin,
    disable_plugin as manager_disable_plugin,
)
from apps.modules.admin.services.sys.plugin_service import PluginService

plugin_manager_bp = Blueprint('plugin_manager', __name__, url_prefix='/plugin_manager')


@plugin_manager_bp.get('/')
def index():
    return render_template('system/plugin_manager/main.html')


@plugin_manager_bp.get('/list')
def get_plugin_list():
    """获取所有插件列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        limit = request.args.get('limit', 20, type=int)
        name = request.args.get('name', '')
        author = request.args.get('author', '')
        blueprint_name = request.args.get('blueprint_name', '')
        status = request.args.get('status', type=int)
        is_installed = request.args.get('is_installed', type=bool)
        is_enabled = request.args.get('is_enabled', type=bool)
        
        query_params = {
            'page': page,
            'limit': limit,
            'name': name if name else None,
            'author': author if author else None,
            'blueprint_name': blueprint_name if blueprint_name else None,
            'status': status,
            'is_installed': is_installed,
            'is_enabled': is_enabled
        }
        
        # 获取插件列表
        plugins, total = PluginService.get_plugins(query_params)
        
        # 转换为字典格式
        data = []
        for plugin in plugins:
            plugin_dict = plugin.to_dict()
            plugin_dict['status_text'] = plugin.get_status_text()
            plugin_dict['status_class'] = plugin.get_status_class()
            plugin_dict['file_size_text'] = plugin.get_file_size_text()
            data.append(plugin_dict)
        
        return jsonify({
            'code': 0,
            'msg': '',
            'count': total,
            'data': data
        })
        
    except Exception as e:
        return jsonify({
            'code': 1,
            'msg': f'获取插件列表失败: {str(e)}',
            'count': 0,
            'data': []
        })


@plugin_manager_bp.get('/info/<int:plugin_id>')
def get_plugin_info(plugin_id):
    """获取指定插件的详细信息"""
    try:
        plugin = PluginService.get_plugin_by_id(plugin_id)
        
        if not plugin:
            return jsonify({
                'success': False,
                'msg': f'插件不存在'
            })
        
        plugin_dict = plugin.to_dict()
        plugin_dict['status_text'] = plugin.get_status_text()
        plugin_dict['status_class'] = plugin.get_status_class()
        plugin_dict['file_size_text'] = plugin.get_file_size_text()
        
        return jsonify({
            'success': True,
            'data': plugin_dict
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'获取插件信息失败: {str(e)}'
        })


@plugin_manager_bp.post('/upload')
def upload_plugin():
    """上传并安装插件"""
    try:
        # 检查是否有文件上传
        if 'file' not in request.files:
            return jsonify({
                'success': False,
                'msg': '请选择插件文件'
            })
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({
                'success': False,
                'msg': '请选择插件文件'
            })
        
        # 获取插件名称（可选）
        plugin_name = request.form.get('plugin_name')
        
        # 上传插件
        result = upload_plugin_dynamic(file, plugin_name)
        if result['success']:
            PluginService.create_plugin(result['plugin'])

        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'上传插件失败: {str(e)}'
        })


@plugin_manager_bp.post('/uninstall/<int:plugin_id>')
def uninstall_plugin(plugin_id):
    """卸载插件"""
    try:
        plugin = PluginService.get_plugin_by_id(plugin_id)
        if not plugin:
            return jsonify({
                'success': False,
                'msg': '插件不存在'
            })
        
        success, message = PluginService.uninstall_plugin(plugin_id)
        
        return jsonify({
            'success': success,
            'msg': message
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'卸载插件失败: {str(e)}'
        })


@plugin_manager_bp.post('/create')
def create_plugin():
    """创建插件"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'success': False,
                'msg': '请求数据不能为空'
            })
        
        success, message, plugin = PluginService.create_plugin(data)
        
        return jsonify({
            'success': success,
            'msg': message,
            'data': plugin.to_dict() if plugin else None
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'创建插件失败: {str(e)}'
        })


@plugin_manager_bp.post('/update/<int:plugin_id>')
def update_plugin(plugin_id):
    """更新插件"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'success': False,
                'msg': '请求数据不能为空'
            })
        
        success, message, plugin = PluginService.update_plugin(plugin_id, data)
        
        return jsonify({
            'success': success,
            'msg': message,
            'data': plugin.to_dict() if plugin else None
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'更新插件失败: {str(e)}'
        })


@plugin_manager_bp.post('/delete/<int:plugin_id>')
def delete_plugin(plugin_id):
    """删除插件"""
    try:
        plugin = PluginService.get_plugin_by_id(plugin_id)
        if not plugin:
            return jsonify({
                'success': False,
                'msg': '插件不存在'
            })
        
        success, message = PluginService.delete_plugin(plugin_id)
        
        return jsonify({
            'success': success,
            'msg': message
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'删除插件失败: {str(e)}'
        })


@plugin_manager_bp.post('/enable/<int:plugin_id>')
def enable_plugin(plugin_id):
    """启用插件"""
    try:
        plugin = PluginService.get_plugin_by_id(plugin_id)
        if not plugin:
            return jsonify({
                'success': False,
                'msg': '插件不存在'
            })
        
        success, message = PluginService.enable_plugin(plugin_id)
        if success:
            manager_enbable_plugin(plugin.name)
        return jsonify({
            'success': success,
            'msg': message
        })
        
    except Exception as e:
        print(e)
        return jsonify({
            'success': False,
            'msg': f'启用插件失败: {str(e)}'
        })


@plugin_manager_bp.post('/disable/<int:plugin_id>')
def disable_plugin(plugin_id):
    """禁用插件"""
    try:
        plugin = PluginService.get_plugin_by_id(plugin_id)
        if not plugin:
            return jsonify({
                'success': False,
                'msg': '插件不存在'
            })
        
        success, message = PluginService.disable_plugin(plugin_id)
        if success:
            manager_disable_plugin(plugin.name)
        return jsonify({
            'success': success,
            'msg': message
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'禁用插件失败: {str(e)}'
        })


@plugin_manager_bp.get('/logs')
def get_plugin_logs():
    """获取插件操作日志"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        limit = request.args.get('limit', 20, type=int)
        plugin_id = request.args.get('plugin_id', type=int)
        operation = request.args.get('operation', '')
        operator = request.args.get('operator', '')
        success = request.args.get('success', type=bool)
        
        query_params = {
            'page': page,
            'limit': limit,
            'plugin_id': plugin_id,
            'operation': operation if operation else None,
            'operator': operator if operator else None,
            'success': success
        }
        
        # 获取日志列表
        logs, total = PluginService.get_plugin_logs(query_params)
        
        # 转换为字典格式
        data = [log.to_dict() for log in logs]
        
        return jsonify({
            'code': 0,
            'msg': '',
            'count': total,
            'data': data
        })
        
    except Exception as e:
        return jsonify({
            'code': 1,
            'msg': f'获取插件日志失败: {str(e)}',
            'count': 0,
            'data': []
        })


@plugin_manager_bp.get('/template')
def get_plugin_template():

    """获取插件模板信息"""
    try:
        template = {
            'name': '示例插件',
            'version': '1.0.0',
            'description': '这是一个示例插件',
            'author': '开发者',
            'blueprint_name': 'example_bp',
            'url_prefix': '/example',
            'files': [
                'plugin.json',
                '__init__.py',
                'example_bp.py'
            ],
            'plugin.json': {
                'name': '示例插件',
                'version': '1.0.0',
                'description': '这是一个示例插件',
                'author': '开发者',
                'blueprint_name': 'example_bp',
                'url_prefix': '/example'
            },
            '__init__.py': '# 插件初始化文件\n# 可以在这里进行插件的初始化工作',
            'example_bp.py': '''from flask import Blueprint, jsonify

# 创建蓝图
example_bp = Blueprint('example', __name__, url_prefix='/example')

@example_bp.route('/')
def index():
    """示例路由"""
    return jsonify({
        'message': '这是一个示例插件',
        'status': 'success',
        'plugin': 'example_plugin'
    })

@example_bp.route('/hello')
def hello():
    """Hello路由"""
    return jsonify({
        'message': 'Hello from example plugin!',
        'status': 'success'
    })'''
        }
        
        return jsonify({
            'success': True,
            'data': template
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'获取插件模板失败: {str(e)}'
        }) 